<template>
	<view class="container">
		<view class="box-form">
			<u--form
			labelPosition="left"
			:model="data"
			:rules="rules"
			ref="uForm">
				<u-form-item
					labelWidth="100"
					label="标题:"
					prop="title">
					<u--input prefixIconStyle="font-size: 22px;color: #909399" v-model="data.title" placeholder="文章标题"></u--input>
				</u-form-item>
				<u-form-item
					labelWidth="100"
					label="内容:"
					prop="content">
					<u--textarea height="350" :maxlength="-1" v-model="data.content" placeholder="文章内容" confirmType="done"></u--textarea>
				</u-form-item>
				<u-form-item
					labelWidth="100"
					label="状态:"
					prop="state">
					<u-switch v-model="data.state" size="35" activeValue="1" inactiveValue="0" inactiveColor="#C00000" activeColor="#5AC725"></u-switch>
				</u-form-item>
				<u-form-item
					labelWidth="100"
					label="归类:"
					prop="author_id">
					<view style="width: 100%;position: relative;" @click="onPickerHidden">
						<u--input
						   placeholder="文章归类"
						   border="surround"
						   v-model="data.author_mc"
						 ></u--input>
						 <view class="box-view"></view>
					</view>
				</u-form-item>
				<u-form-item
					labelWidth="100"
					label="图片:"
					prop="cover_img">
					<view class="upload-image">
						<view @click="startUpload" style="position: relative;">
							<view class="box-view"></view>
						  	<u-upload
						  		:action="data.cover_img"
						  		:file-list="fileList"
						  		@afterRead="uploadAfterRead"
						  		:maxCount="1"
						  		height="200"
						  		width="200"
						  		:deletable="false"
						  		:previewFullImage="false"
						  		:useBeforeRead="true"
						  		ref="upload"
						  	></u-upload>
						</view>
						<view>
							<u--input
							  placeholder="图片URL地址"
							  border="surround"
							  v-model="data.cover_img"
							></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item
					labelWidth="100"
					label="作者:"
					prop="pub_date">
					<u--input prefixIconStyle="font-size: 22px;color: #909399" v-model="data.pub_date" placeholder="文章作者"></u--input>
				</u-form-item>
			</u--form>
			<u-button class="box-sign-in" @click="submit" color="#C00000" loadingMode="semicircle" :loading="loading" loadingText="更改中..." loadingSize="60">更 改</u-button>
			<u-button class="box-sign-in" @click="textDelete()" style="margin-bottom: 40rpx;">删 除</u-button>
		</view>
		<u-picker title="文章归类" confirmColor="#C00000" :show="pickerHidden" :columns="columnsList" itemHeight="100" @cancel="cancelPicker" @confirm="confirmPicker"></u-picker>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="showModal" title="提示" cancelText="关闭" content="是否确定删除?" confirmColor="#C00000" :asyncClose="true" @cancel="cancelDelete" @confirm="confirmDelete" showCancelButton showConfirmButton></u-modal>
	</view>
</template>

<script>
	import { articleCates , articleTextUpdate , articleTextDelete } from '@/api/getList.js';
	export default {
		data() {
			return {
				showModal: false,
				action: "",
				fileList: [],
				loading: false,
				pickerHidden: false,
				columnsList: [],
				articleCatesList: [],
				data: {
					title: "",// 标题
					content: "",// 内容
					state: "1",// 状态
					cate_id: `${ new Date().getTime() }`,// 整数文章id
					author_id: "",// 文章归类id
					author_mc: "",// 文章归类名称
					cover_img: "",// 内容图片地址
					pub_date: ""// 作者
				},
				rules: {
					'title': {
						type: 'string',
						required: true,
						message: '请输入标题',
						trigger: ['blur']
					},
					'content': {
						type: 'string',
						required: true,
						message: '请输入内容',
						trigger: ['blur']
					},
					'pub_date': {
						type: 'string',
						required: true,
						message: '请输入作者',
						trigger: ['blur']
					},
					'cover_img': {
						type: 'string',
						required: true,
						message: '请输入图片地址',
						trigger: ['blur']
					}
				}
			}
		},
		created() {
			this.getArticleCates(({ articleCatesList , nameList }) => {
				const item = uni.getStorageSync("item");
				const data = item;
				const [row] = articleCatesList.filter(row => row.Id === data.author_id);
				this.data.author_mc = row.name;
				this.fileList = [{ url: data.cover_img }];
				this.$set(this.data,'title',data.title);
				this.$set(this.data,'content',data.content);
				this.$set(this.data,'cate_id',data.cate_id);
				this.$set(this.data,'author_id',data.author_id);
				this.$set(this.data,'cover_img',data.cover_img);
				this.$set(this.data,'pub_date',data.pub_date);
				this.$set(this.data,'state',data.state);
				this.$set(this.data,'Id',data.Id);
			});
		},
		methods: {
			async confirmDelete(){
				const data = await articleTextDelete({ Id: this.data.Id });
				this.$refs.uToast.show({ message: data.message });
				let dateTime = setTimeout(() => {
					uni.navigateBack();
					clearTimeout(dateTime);
				},1500);
			},
			cancelDelete(){
				this.showModal = false;
			},
			textDelete(){
				this.showModal = true;
			},
			startUpload(){
				this.$refs.upload.chooseFile();
			},
			uploadAfterRead({ file }, fileList) {
			  const _this = this;
			  _this.fileList = [];
			  let lists = [].concat(file)
			  let fileListLen = this[`fileList`].length
			  lists.map((item) => {
			  	_this[`fileList`].push({
			  		...item,
			  		status: 'uploading',
			  		message: '更新中'
			  	})
			  });
			  fetch(file.url).then(res => res.arrayBuffer()).then(arrayBuffer => {
			    const base64 = uni.arrayBufferToBase64(arrayBuffer);
			    const dataUrl = 'data:image/jpeg;base64,' + base64;
				let item = _this[`fileList`][fileListLen]
				_this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
					status: '',
					message: '',
					url: dataUrl
				}));
				_this.action = dataUrl;
				_this.data.cover_img = dataUrl;
			  });
			},
			onPickerHidden(){
				this.pickerHidden = true;
			},
			cancelPicker(){
				this.pickerHidden = false;
			},
			confirmPicker({ indexs , value }){
				this.pickerHidden = false;
				const [data] = value;
				const [index] = indexs;
				this.data.author_mc = data;
				this.data.author_id = `${ this.articleCatesList[index].Id }`;
			},
			async getArticleCates(MiXi){
				const { data } = await articleCates({ value: "" });
				this.articleCatesList = data;
				this.columnsList = [data.map(item => item.name)];
				if(typeof MiXi === 'function')return MiXi({ articleCatesList: data , nameList: data.map(item => item.name)});
			},
			// 保存
			submit(){
				if(!this.data.author_id)return this.$refs.uToast.show({ message: '文章归类必须填写' });
				this.data.cate_id = `${ new Date().getTime() }`;
				this.data.author_id = `${ this.data.author_id }`;
				this.$refs.uForm.validate().then(async res => {
					this.loading = true;
					const data = await articleTextUpdate(this.data);
					this.$refs.uToast.show({ message: data.message });
					this.loading = false;
				}).catch(errors => {
					this.loading = false;
				});
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		}
	}
</script>

<style lang="scss" scoped>
	page {
		box-sizing: border-box;
		background-color: #FFFFFF;
	}
	.container {
		width: 100%;
		box-sizing: border-box;
		padding: 0 40rpx;
		min-height: calc(100vh);
		background-color: #FFFFFF;
	}
	.box-form {
		padding-top: 10rpx;
	}
	.box-sign-in {
		height: 70rpx;
		margin-top: 20rpx;
	}
	.box-view {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: 1;
		top: 0;
	}
	.upload-image {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>
